<template>
  <div class="stock-container">
    <div class="search-section animate__animated animate__fadeInDown">
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入溯源码" v-model="traceCode" prefix-icon="el-icon-document"></el-input>
      <el-input style="width: 200px;margin-right: 20px" placeholder="请输入商品名称" v-model="productName" prefix-icon="el-icon-goods"></el-input>
      <el-button style="margin-left: 10px;" type="primary" @click="load" class="el-icon-search">搜索</el-button>
      <el-button style="margin-left: 10px;" type="warning" @click="reset" class="el-icon-refresh">重置</el-button>
      <el-button style="margin-left: 10px;" type="success" @click="handleBatchUpdate" class="el-icon-upload">批量更新库存</el-button>
    </div>

    <div class="table-section animate__animated animate__fadeInUp">
      <el-table
          :data="tableData" border stripe
          :header-cell-style="getRowClass"
          @selection-change="handleSelectionChange"
          row-key="id">
        
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="productId" label="商品ID"></el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <el-table-column prop="traceCode" label="溯源码"></el-table-column>
        <el-table-column prop="currentStock" label="当前库存量">
          <template slot-scope="scope">
            <span :class="{ 'stock-warning': scope.row.currentStock < 10 }">{{ scope.row.currentStock }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="minTemp" label="最低温度"></el-table-column>
        <el-table-column prop="maxTemp" label="最高温度"></el-table-column>
        <el-table-column prop="origin" label="原产地"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <div class="operation-buttons">
              <el-button size="mini" type="primary" class="el-icon-goods" @click="handleUpdateStock(scope.row)">更新库存</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="block" style="padding:10px 0;align-content: center;margin-left: 30%;margin-top:30px;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 库存更新对话框 -->
    <el-dialog title="更新库存" :visible.sync="stockDialogVisible" width="30%">
      <el-form :model="stockForm" :rules="stockRules" ref="stockForm" label-width="100px">
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="stockForm.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="stockForm.productName" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前库存量" prop="currentStock">
          <el-input v-model="stockForm.currentStock" disabled></el-input>
        </el-form-item>
        <el-form-item label="新库存量" prop="newStock">
          <el-input-number v-model="stockForm.newStock" :min="0" :precision="0"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="stockDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateStock">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量更新库存对话框 -->
    <el-dialog title="批量更新库存" :visible.sync="batchUpdateDialogVisible" width="40%">
      <div v-if="multipleSelection.length === 0" class="empty-selection">
        <i class="el-icon-warning-outline"></i>
        <p>请先选择要更新的商品</p>
      </div>
      <el-table
          v-else
          :data="multipleSelection"
          border
          stripe
          class="batch-table">
        <el-table-column prop="productId" label="商品ID" width="120"></el-table-column>
        <el-table-column prop="productName" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="currentStock" label="当前库存量" width="120"></el-table-column>
        <el-table-column label="新库存量" width="150">
          <template slot-scope="scope">
            <el-input-number 
              v-model="scope.row.newStock" 
              :min="0" 
              :precision="0"
              size="small">
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateBatchStock">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'animate.css/animate.min.css';

export default {
  name: "StockManagement",
  data() {
    return {
      pageSize: 10,
      pageNum: 1,
      traceCode: '',
      productName: '',
      tableData: [],
      stockDialogVisible: false,
      batchUpdateDialogVisible: false,
      stockForm: {
        productId: '',
        productName: '',
        currentStock: 0,
        newStock: 0
      },
      total: 0,
      multipleSelection: [],
      stockRules: {
        newStock: [
          { required: true, message: '请输入新库存数量', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      // 加载商品和库存信息
      this.request.get("/product/list").then(res => {
        if (res.code === '200') {
          // 获取所有商品
          const products = res.data || [];
          
          // 将商品信息格式化，并添加库存默认值
          this.tableData = products.map(product => {
            return {
              productId: product.productId,
              productName: product.productName,
              traceCode: product.traceCode,
              minTemp: product.minTemp,
              maxTemp: product.maxTemp,
              origin: product.origin,
              currentStock: 0, // 默认库存为0，后续查询更新
              newStock: 0
            };
          });
          
          // 获取所有商品的库存信息
          this.loadStockInfo();
          
          this.total = products.length;
        }
      });
    },
    
    // 加载库存信息
    loadStockInfo() {
      const promises = this.tableData.map(product => {
        return this.request.get("/warehouse/findByTraceCode/" + product.traceCode)
          .then(res => {
            if (res.code === '200' && res.data) {
              // 更新当前商品的库存
              product.currentStock = res.data.amount || 0;
              product.newStock = res.data.amount || 0;
            }
            return product;
          })
          .catch(() => {
            // 请求失败保持默认值
            return product;
          });
      });
      
      // 等待所有请求完成后更新表格
      Promise.all(promises).then(updatedProducts => {
        this.tableData = updatedProducts;
        
        // 根据搜索条件过滤
        if (this.traceCode) {
          this.tableData = this.tableData.filter(item => 
            item.traceCode && item.traceCode.includes(this.traceCode)
          );
        }
        if (this.productName) {
          this.tableData = this.tableData.filter(item => 
            item.productName && item.productName.includes(this.productName)
          );
        }
      });
    },
    
    getRowClass({rowIndex, columnIndex}) {
      if(rowIndex === 0) {
        return 'background:#ccc'
      }
    },
    
    reset() {
      this.traceCode = '';
      this.productName = '';
      this.load();
    },
    
    // 处理更新库存按钮点击
    handleUpdateStock(row) {
      this.stockForm = {
        productId: row.productId,
        productName: row.productName,
        currentStock: row.currentStock,
        newStock: row.currentStock
      };
      this.stockDialogVisible = true;
    },
    
    // 更新单个商品库存
    updateStock() {
      this.$refs.stockForm.validate((valid) => {
        if (valid) {
          this.request.put("/warehouse/updateStock/" + this.stockForm.productId, {
            amount: this.stockForm.newStock
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('库存更新成功');
              this.stockDialogVisible = false;
              this.load();
            } else {
              this.$message.error(res.msg || '库存更新失败');
            }
          }).catch(err => {
            this.$message.error('更新库存时发生错误');
            console.error(err);
          });
        }
      });
    },
    
    // 打开批量更新对话框
    handleBatchUpdate() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择需要更新的商品');
      }
      this.batchUpdateDialogVisible = true;
    },
    
    // 批量更新库存
    updateBatchStock() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要更新的商品');
        return;
      }
      
      // 创建批量更新的Promise数组
      const updatePromises = this.multipleSelection.map(item => {
        return this.request.put("/warehouse/updateStock/" + item.productId, {
          amount: item.newStock
        });
      });
      
      // 执行所有更新
      Promise.all(updatePromises)
        .then(() => {
          this.$message.success('批量更新库存成功');
          this.batchUpdateDialogVisible = false;
          this.load();
        })
        .catch(err => {
          this.$message.error('批量更新库存时发生错误');
          console.error(err);
        });
    },
    
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
    handleSizeChange(val) {
      this.pageSize = val;
      this.load();
    },
    
    handleCurrentChange(val) {
      this.pageNum = val;
      this.load();
    }
  }
}
</script>

<style scoped>
.stock-container {
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.table-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.operation-buttons {
  display: flex;
  gap: 5px;
}

.el-button {
  margin: 0;
}

.el-table {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.stock-warning {
  color: #E6A23C;
  font-weight: bold;
}

.batch-table {
  margin-top: 15px;
}

.empty-selection {
  text-align: center;
  padding: 30px 0;
}

.empty-selection i {
  font-size: 48px;
  color: #E6A23C;
}

.empty-selection p {
  margin-top: 10px;
  color: #606266;
}
</style> 